<template>
  <div class="app-container">
    <div class="head">
      <span style="float:left;">{{ $t('area.Layer') }}:</span>
      <treeselect
        v-model="mapId"
        :class="{treeps:isDisable}"
        :disabled="isDisable"
        :placeholder=" $t('area.chosenLayer')"
        :max-height="300"
        :options="mapList"
        style="float:left;width:200px;"
        @input="nodeClick"
      />
      <span style="margin-left:20px;">{{ $t('operating.operating') }}:</span>
      <span>
        <el-tooltip
          v-for="(item,index) in $t('camera.drawForms')"
          :key="index"
          effect="dark"
          :content="item.label"
          placement="bottom"
        >
          <el-button
            :key="item.value"
            type="text"
            :autofocus="false"
            :data-id="item.value"
            :label="item.label"
            :disabled="disabled"
            size="mini"
            @click="handleChange(index,item.value)"
          >
            <i :class="[item.id==colorFlag?item.unIconFont:item.iconFont]" />
          </el-button>
        </el-tooltip>
      </span>
    </div>
    <div id="map" />

    <!--新增围栏-->
    <el-drawer
      custom-class="changeDialog"
      :title="title_"
      :visible.sync="fenceEditVisible"
      direction="rtl"
      :modal-append-to-body="true"
      size="100%"
      :modal="false"
      @open="disabled=true"
      @close="closeDialog"
    >
      <el-form label-width="120px">
        <el-form-item>
          <el-button
            type="primary"
            @click="saveFenceEdit"
          >{{ $t('operating.determine') }}</el-button>
          <el-button
            type="danger"
            @click="deleteForm"
          >{{ oparts }}</el-button>
        </el-form-item>
        <el-form-item
          :label="$t('camera.cameraName')"
          :rules="[
            { required: true, message: '', trigger: 'blur' },
          ]"
        >
          <el-input v-model="cameraName" />
        </el-form-item>
        <el-form-item
          :label="$t('camera.cameraIp')"
          :rules="[
            { required: true, message: '', trigger: 'blur' },
          ]"
        >
          <el-input v-model="cameraIp" />
        </el-form-item>
        <el-form-item
          :label="$t('camera.cameraPort')"
          :rules="[
            { required: true, message: '', trigger: 'blur' },
          ]"
        >
          <el-input v-model="cameraPort" />
        </el-form-item>
        <el-form-item
          :label="$t('camera.cameraUser')"
          :rules="[
            { required: true, message: '', trigger: 'blur' },
          ]"
        >
          <el-input v-model="cameraUser" />
        </el-form-item>
        <el-form-item
          :label="$t('camera.cameraPwd')"
          :rules="[
            { required: true, message: '', trigger: 'blur' },
          ]"
        >
          <el-input v-model="cameraPwd" />
        </el-form-item>
        <el-form-item
          :label="$t('camera.cameraVendor')"
          :rules="[
            { required: true, message: '', trigger: 'blur' },
          ]"
        >
          <el-select
            v-model="cameraVendor"
            :placeholder="$t('operating.pleaseChosen')"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('camera.cameraFenceList')"
        >
          <el-select
            v-model="fenceIdx"
            :placeholder="$t('operating.pleaseChosen')"
            style="width: 100%"
          >
            <el-option
              v-for="item in cameraFenceList"
              :key="item.idx"
              :label="item.fenceName"
              :value="item.idx"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="X">
          <el-input-number
            v-model="postX"
            controls-position="right"
            style="width:100%"
            :step="0.1"
            @change="changeArr"
          />
        </el-form-item>
        <el-form-item label="Y">
          <el-input-number
            v-model="postY"
            controls-position="right"
            style="width:100%"
            :step="0.1"
            @change="changeArr"
          />
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 左下角坐标显示和缩放比例 -->
    <div class="positiondiv">
      <span />
    </div>
    <div class="scalediv">
      <span />
    </div>
    <!-- 显示坐标方向示意图 -->
    <div class="zuobiao" />
  </div>

</template>

<script>
import i18n from '@/utils/lang/index'

import { GeoJSON } from 'ol/format.js'
import { Draw, Modify, Snap, Select, Translate } from 'ol/interaction.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import { createRegularPolygon, createBox } from 'ol/interaction/Draw.js'
import { altKeyOnly, click, pointerMove } from 'ol/events/condition'
import {
  Image
} from 'ol/layer.js'
import {
  ImageStatic
} from 'ol/source.js'
import Overlay from 'ol/Overlay'
import {
  Projection
} from 'ol/proj.js'
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { baseUrl } from '@/utils/global'
import Cookie from 'js-cookie'
import axios from 'axios'
// import gratiClue from '../../../static/map/009.png'
import { OSM, Vector as VectorSource } from 'ol/source'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import {
  Style,
  Icon,
  Text,
  Fill,
  Stroke,
  Circle as CircleStyle
} from 'ol/style'
import { getLength } from 'ol/sphere'
import {
  sendThis,
  Load_Map,
  _iMap,
  _TransPixel,
  _Style,
  _TransMetric,
  _TransMetric2,
  _TransMetric3,
  _TransMetricFence,
  _dPR,
  Load_Camera,
  Load_Camera2,
  cameraSource,
  cameraSource2,
  Load_CameraFence
} from '@/utils/historyMap.js'
import {
  getMapTree,
  getMap
} from '@/api/location'
import {
  getCameraFenceDataList,
  addCamera,
  delCameraInfo
} from '@/api/system/historyDisplayInfo.js'
export default {
  components: { Treeselect }, // 注册树形穿梭框组件
  data() {
    return {
      mapId: null,
      mapList: [],
      colorFlag: 0,
      drawFormValue: 'None', // 绘制形状
      draw: null,
      fenceEditVisible: false,
      cameraName: null,
      cameraIp: null,
      cameraPort: null,
      cameraUser: null,
      cameraPwd: null,
      cameraVendor: null,
      fenceType: null,
      mapName: null,
      Geo: null,
      disabled: false,
      options: [{ label: '海康威视', value: '0' }, { label: '大华', value: '1' }, { label: '华为', value: '2' }, { label: 'TP-LINK', value: '3' }],
      cameraFenceList: [],
      fenceIdx: null,
      postX: null,
      postY: null,
      modify: null,
      cameraId: null,
      oparts: i18n.t('operating.cancel'),
      coors3: null,
      select_: null,
      title_: i18n.t('operating.add'),
      isDisable: false// 是否禁用图层选择
    }
  },
  // 钩子
  mounted() {
    this.init()
  },
  methods: {
    init() {
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        if (typeof RES !== 'undefined') {
          this.mapList = RES
          sendThis(this)
          this.mapId = RES[0].id
        }
      })
    },
    nodeClick() {
      const self = this
      if (self.mapId === '' || self.mapId === undefined || self.mapId === null) {
        if (self.draw != null) {
          _iMap.removeInteraction(self.draw)
        }
        if (self.select_ != null) {
          _iMap.removeInteraction(self.select_)
        }

        return
      }
      getMap(self.mapId).then(res => {
        const RES = self.responseUse(res)
        if (RES != undefined) {
          $('#map').empty()
          self.mapName = RES.mapName
          Load_Map(baseUrl + '/file' + RES.mapPath, RES.mapActualX,
            RES.mapActualY,
            RES.mapPixelX,
            RES.mapPixelY,
            RES.mapPixelX / RES.mapActualX, [RES.mapOriginX, RES.mapOriginY], false)
          getCameraFenceDataList(self.mapId).then(res => {
            const RES = self.responseUse(res)
            if (RES != undefined) {
              self.cameraFenceList = RES
            }
          })
          Load_CameraFence(self.mapId)
          Load_Camera(self.mapId)
          Load_Camera2()
          self.fenceModify_init()
        }
      })
    },
    handleChange(val, type) {
      this.colorFlag = val
      this.drawFormValue = type
      this.fenceModify_init()
    },
    fenceModify_init() {
      const self = this
      if (self.draw != null) {
        _iMap.removeInteraction(self.draw)
      }
      if (self.select_ != null) {
        _iMap.removeInteraction(self.select_)
      }

      if (self.mapId === '' || self.mapId === undefined || self.mapId === null) {
        this.msgError(this.$i18n.t('Notice.mapIDIsEmpty'))
        return
      }

      if (self.drawFormValue == 'None') {} else if (self.drawFormValue == 'Point') {
        self.oparts = i18n.t('operating.cancel')
        self.title_ = i18n.t('operating.add')
        self.draw = new Draw({
          source: cameraSource2,
          type: 'Point'
        })
        _iMap.addInteraction(self.draw)
        self.draw.on('drawend', function(evt) {
          self.modify = new Modify({
            source: cameraSource2
          })
          _iMap.addInteraction(self.modify)
          self.modify.on('modifyend', function(e) {
            const f = e.features.array_[0]
            const coors2 = f.get('geometry').getCoordinates()
            self.postX = (coors2[0] / _dPR).toFixed(2)
            self.postY = (coors2[1] / _dPR).toFixed(2)
            self.coors3 = '[' + _TransMetric(coors2).toString() + ']'
          })
          if (self.cameraId == 'temporary') {
            self.$confirm(i18n.t('operating.drawRect'), i18n.t('operating.prompt'), {
              confirmButtonText: i18n.t('common.cok'),
              cancelButtonText: i18n.t('operating.cancel'),
              type: 'warning'
            }).then(() => {
              cameraSource2.removeFeature(cameraSource2.getFeatureById('temporary'))
              self.cameraId = 'temporary'
              evt.feature.setId('temporary')
              const coors = evt.feature.getGeometry().getCoordinates()
              self.postX = (coors[0] / _dPR).toFixed(2)
              self.postY = (coors[1] / _dPR).toFixed(2)
              self.coors3 = '[' + _TransMetric(coors).toString() + ']'
            }).catch(() => {
              cameraSource2.removeFeature(cameraSource2.getFeatures()[1])
            })
          } else {
            self.cameraId = 'temporary'
            evt.feature.setId('temporary')
            const coors = evt.feature.getGeometry().getCoordinates()
            // console.log(coors)
            self.postX = (coors[0] / _dPR).toFixed(2)
            self.postY = (coors[1] / _dPR).toFixed(2)
            // console.log(self.postX, self.postY)
            self.coors3 = '[' + _TransMetric(coors).toString() + ']'
            self.fenceEditVisible = true
            self.isDisable = true
          }
        })
      } else if (self.drawFormValue == 'Select') {
        self.title_ = i18n.t('operating.handle')
        self.oparts = i18n.t('operating.delete')
        self.select_ = new Select({
          condition: click,
          layers: function(e) {
            if (e.className_ == 'camera') {
              return true
            } else {
              return false
            }
          }
        })
        _iMap.addInteraction(self.select_)
        self.modify = new Modify({
          features: self.select_.getFeatures()
        })
        _iMap.addInteraction(self.modify)
        self.modify.on('modifyend', function(e) {
          const f = e.features.array_[0]
          const coors2 = f.get('geometry').getCoordinates()
          self.postX = (coors2[0] / _dPR).toFixed(2)
          self.postY = (coors2[1] / _dPR).toFixed(2)
          self.coors3 = '[' + _TransMetric(coors2).toString() + ']'
        })
        self.select_.on('select', function(e) {
          if (e.selected.length > 0) {
            e.selected.forEach(function(f) {
              self.cameraId = f.get('idx')
              self.cameraIp = f.get('cameraIp')
              self.cameraName = f.get('cameraName')
              self.cameraUser = f.get('cameraUser')
              self.cameraPwd = f.get('cameraPwd')
              self.cameraVendor = f.get('cameraVendor')
              self.sourceType = f.get('sourceType')
              self.cameraPort = f.get('cameraPort')
              self.postX = f.get('posX')
              self.postY = f.get('posY')
              self.fenceIdx = f.get('fenceId')
              self.coors3 = [self.postX, self.postY]
            })
            self.fenceEditVisible = true
            self.isDisable = true
          }
        })
      }
    },
    changeArr() {
      if (this.cameraId == 'temporary') {
        const currentFeature = cameraSource2.getFeatureById('temporary')
        currentFeature.getGeometry().setCoordinates([this.postX * _dPR, this.postY * _dPR])
      } else {
        const currentFeature = cameraSource.getFeatureById(this.cameraId)
        currentFeature.getGeometry().setCoordinates(_TransPixel([this.postX, this.postY]))
        this.coors3 = [this.postX, this.postY]
      }
    },
    closeDialog() {
      const self = this
      self.isDisable = false
      self.disabled = false
      Load_Camera(self.mapId)
      self.cameraId = null
      cameraSource2.clear()
      if (self.modify != null) {
        _iMap.removeInteraction(self.modify)
      }
      self.fenceModify_init()
      self.cameraId = null
      self.cameraIp = null
      self.cameraName = null
      self.cameraUser = null
      self.cameraPwd = null
      self.cameraVendor = null
      self.cameraPort = null
      self.fenceIdx = null
      self.coors3 = null
    },
    saveFenceEdit() {
      const patrn = /^(-)?\d+(\.\d+)?$/
      if (this.cameraPort == null || this.cameraPort == '') {
        this.$message({
          message: i18n.t('realtime.cameraPortMasg'),
          type: 'error'
        })
        return
      } else if (patrn.exec(this.cameraPort) == null || this.cameraPort.indexOf('.') != -1) {
        this.$message({
          message: i18n.t('realtime.cameraPortMasg'),
          type: 'error'
        })
        return
      }
      let param = {}
      if (this.cameraId == 'temporary') {
        param = {
          'cameraIp': this.cameraIp,
          'cameraName': this.cameraName,
          'cameraUser': this.cameraUser,
          'cameraPwd': this.cameraPwd,
          'cameraVendor': this.cameraVendor,
          'sourceType': 'RTSP',
          'cameraPort': this.cameraPort,
          'posX': eval(this.coors3)[0],
          'posY': eval(this.coors3)[1],
          'fenceId': this.fenceIdx,
          'layerId': this.mapId
        }
      } else {
        param = {
          'cameraIp': this.cameraIp,
          'cameraName': this.cameraName,
          'cameraUser': this.cameraUser,
          'cameraPwd': this.cameraPwd,
          'cameraVendor': this.cameraVendor,
          'sourceType': 'RTSP',
          'cameraPort': this.cameraPort,
          'posX': eval(this.coors3)[0],
          'posY': eval(this.coors3)[1],
          'fenceId': this.fenceIdx,
          'layerId': this.mapId,
          'idx': this.cameraId
        }
      }
      addCamera(param).then(res => {
        const RES = this.responseUse(res)
        if (RES == 1) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.fenceEditVisible = false
          this.isDisable = false
        }
      })
    },
    deleteForm() {
      if (this.cameraId == 'temporary') {
        this.fenceEditVisible = false
        this.isDisable = false
      } else {
        this.$confirm(i18n.t('operating.deletePrompt'), i18n.t('operating.prompt'), {
          confirmButtonText: i18n.t('common.cok'),
          cancelButtonText: i18n.t('operating.cancel'),
          type: 'warning'
        }).then(() => {
          delCameraInfo([{ 'idx': this.cameraId }]).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.fenceEditVisible = false
            this.isDisable = false
          })
        }).catch(() => {

        })
      }
    }
  }
}
</script>

<style scoped>
::v-deep .el-drawer__wrapper {
  width: 400px;
  left: unset;
}
.head {
  width: 100%;
  height: 50px;
  box-sizing: border-box;
}
.head span {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  color: #606266;
  padding: 0 12px 0 0;
  font-weight: 700;
}
#map {
  width: 100%;
  height: calc(100% - 50px);
  background: rgb(238, 238, 238);
}

>>> .ol-tooltip {
  position: relative;
  background: rgba(255, 238, 2, 1);
  border-radius: 4px;
  color: black;
  padding: 4px 8px;
  opacity: 1;
  white-space: nowrap;
  font-size: 12px;
}

.ol-tooltip {
  position: relative;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  color: white;
  padding: 4px 8px;
  opacity: 0.7;
  white-space: nowrap;
  font-size: 12px;
}
>>> .ol-tooltip-measure {
  opacity: 1;
  font-weight: bold;
}
>>> .ol-tooltip-static {
  background-color: #ffcc33;
  color: black;
  border: 1px solid white;
}
>>> .ol-tooltip-measure:before,
>>> .ol-tooltip-static:before {
  border-top: 6px solid rgba(229, 255, 0, 0.8);
  border-right: 6px solid transparent;
  border-left: 6px solid transparent;
  content: "";
  position: absolute;
  bottom: -6px;
  margin-left: -7px;
  left: 50%;
}
>>> .ol-tooltip-static:before {
  border-top-color: #ffcc33;
}

>>> .ol-circle {
  color: white;
  width: 26px;
  height: 26px;
  border-radius: 10px;
  background: rgb(0, 102, 255, 0.7);
  text-align: center;
  line-height: 26px;
}

>>> .el-drawer.rtl {
  overflow: scroll;
}
 /deep/ .treeps .vue-treeselect__single-value{
  color: #c6c6c6;

}
  /deep/ .vue-treeselect.treeps{
  cursor:not-allowed;
}

</style>
